<template>
  <el-dialog
    :close-on-click-modal="false"
    class="register"
    :visible.sync="isShow"
    width="600px"
    :show-close="false"
  >
    <div slot="title" class="re-title">用户注册</div>
    <el-form :model="form" class="register-form" ref="form" :rules="rules" label-width="90px">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseURL+'/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="txcode">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.txcode"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <img @click="getTxcode" class="txcode" :src="baseURL+codeURL" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-button v-if="flag" @click="getCode">获取验证码</el-button>
            <el-button class="btn" disabled v-else>{{time}}秒后获取验证码</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit">确 定</el-button>
      <el-button @click="isShow = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getPhoneCode, toRegister } from "@/api/register";
export default {
  watch: {
    isShow(newVal) {
      if (!newVal) {
        this.$refs.form.resetFields();
        this.imageUrl = "";
        clearInterval(this.timeID);
        this.flag = true;
        this.time = 5;
      }
    },
  },
  data() {
    return {
      time: 5,
      flag: true,
      isShow: false,
      imageUrl: "",
      baseURL: process.env.VUE_APP_URL,
      codeURL: "/captcha?type=sendsms",
      timeID: "",
      form: {
        avatar: "",
        username: "",
        email: "",
        phone: "",
        password: "",
        txcode: "",
        rcode: "",
      },
      rules: {
        avatar: [{ required: true, message: "必填", trigger: "change" }],
        username: [{ required: true, message: "必填", trigger: "change" }],
        email: [
          { required: true, message: "必填", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("邮箱格式错误"));
              }
            },
          },
        ],
        phone: [
          { required: true, message: "必填", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("手机号格式错误"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "必填", trigger: "change" },
          { min: 6, max: 12, message: "请输入6-12位密码", trigger: "change" },
        ],
        txcode: [
          { required: true, message: "必填", trigger: "change" },
          { min: 4, max: 4, message: "请输入4位验证码", trigger: "change" },
        ],
        rcode: [
          { required: true, message: "必填", trigger: "change" },
          { min: 4, max: 4, message: "请输入4位验证码", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    getTxcode() {
      this.codeURL = "/captcha?type=sendsms&aaa=" + Math.random() * 999;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // this.form.avatar = URL.createObjectURL(file.raw);
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    getCode() {
      let num = 0;
      this.$refs.form.validateField(["phone", "txcode"], (err) => {
        // console.log(err);
        if (!err) {
          num++;
        }
      });
      if (num == 2) {
        this.flag = false;
        this.timeID = setInterval(() => {
          this.time--;
          if (this.time <= 0) {
            clearInterval(this.timeID);
            this.flag = true;
            this.time = 5;
          }
        }, 1000);
        let data = {
          code: this.form.txcode,
          phone: this.form.phone,
        };
        getPhoneCode(data).then((res) => {
          // console.log(res);
          if (res.data.code == 200) {
            this.$message.success(res.data.data.captcha + "");
          }
        }).catch(err=>{
          console.log(err);
        })
      } else {
        this.$message.error("请输入手机号或者图形码");
      }
    },

    submit() {
      this.$refs.form.validate((res) => {
        let data = this.form;
        if (res) {
          this.$message.success("验证成功");
          toRegister(data)
            .then((res) => {
              // console.log(res);
              if (res.data.code == 200) {
                this.$message.success("注册成功");
                this.isShow = false;
              } 
            })
            .catch(err=>{
              console.log(err);
            });
        } else {
          this.$message.error("验证失败");
        }
      });
    },
  },
};
</script>
<style>
.el-dialog__header {
  padding: 0;
}
.dialog-footer {
  width: 100%;
  text-align: center;
}
.re-title {
  width: 100%;
  height: 53px;
  line-height: 53px;
  background: linear-gradient(to right, #01c4fa, #1395fa);
  text-align: center;
}
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.txcode {
  width: 100%;
  height: 40px;
}
.btn {
  padding: 12px 10px;
}
</style>